use futures::stream::TryStreamExt;
use mongodb::{
    bson::doc,
    options::{ClientOptions, ServerApi, ServerApiVersion},
    Client, Collection,
};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    sex: String,
}

// 查询
async fn query_user(collection: &Collection<User>) -> mongodb::error::Result<Vec<User>> {
    let mut users = collection.find(doc! {}, None).await?;
    let mut results = Vec::new();
    while let Some(user) = users.try_next().await? {
        results.push(user);
    }
    Ok(results)
}

#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
    let uri = "mongodb://localhost:27017";
    let mut client_options = ClientOptions::parse_async(uri).await?;

    let server_api = ServerApi::builder().version(ServerApiVersion::V1).build();
    client_options.server_api = Some(server_api);

    let client = Client::with_options(client_options)?;

    client
        .database("admin")
        .run_command(doc! { "ping": 1 }, None)
        .await?;
    println!("Pinged your deployment. You successfully connected to MongoDB!");

    let user_coll = client.database("fly-test").collection("users");
    let users = query_user(&user_coll).await?;
    println!("{:?}", users);

    Ok(())
}
